package org.dut.community.controller.advice;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dut.community.util.CommunityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@ControllerAdvice(annotations={Controller.class})
public class ExceptionAdvice {


    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.error("服务器发生异常",e); // 自动打印堆栈信息

        // 判断是否是异步请求（异步请求直接返回错误）
        String xRequestedWith = request.getHeader("x-requested-with");
        if("XMLHttpRequest".equals(xRequestedWith)){
            // 异步请求，返回普通字符串，前端解析为Json
            response.setContentType("application/plain;charset=utf-8");
            response.getWriter().write(CommunityUtil.getJSONString(500,"服务器异常"));
        }else{
            // 同步请求-->重定向到错误页面,同时设置状态码为500
//            request.setAttribute("javax.servlet.error.status_code",500);
            response.sendRedirect(request.getContextPath()+"/error");
        }
    }
}
